package com.aruba.socketlibrary.protocol.handle;

import android.support.annotation.Nullable;

import com.aruba.socketlibrary.config.SerialportConfig;
import com.aruba.socketlibrary.protocol.SendManager.SendResponse;
import com.aruba.socketlibrary.protocol.SocketHelper;
import com.aruba.socketlibrary.protocol.entity.FaceChangeMessage;
import com.aruba.socketlibrary.protocol.entity.TReplyMessage;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by aruba on 2017/10/20.
 * 真实数据的处理
 */

public class DataHandleDelegateImpl implements IDataHandleDelegate {
    private static final String tag = DataHandleDelegateImpl.class.getSimpleName();
    private SocketHelper mSocketHelper;

    private static DataHandleDelegateImpl sInstance;

    public static DataHandleDelegateImpl getInstance() {
        if (sInstance == null) {
            synchronized (DataHandleDelegateImpl.class) {
                if (sInstance == null) {
                    sInstance = new DataHandleDelegateImpl();
                }
            }
        }
        return sInstance;
    }

    @Override
    public synchronized void dataAnalysis(byte nCommand, @Nullable byte nSecondCommand, byte[] realData) {
        int commandId = nCommand & 0xff;

        try {
            switch (commandId) {
                case 0x01:// ISU 通用应答 
                    TReplyMessage message = new TReplyMessage(realData);
                    if (message.Result == 0) {
                        KLog.i(tag, "[平台应答] 成功！");
                    } else {
                        KLog.i(tag, "[平台应答] 失败！");
                    }
                    KLog.i(tag, String.format("中心通用应答,命令字:%04X,结果：%d", message.Command,
                            message.Result
                    ));
                    EventBus.getDefault().post(message);
                    break;
                case 0x02:// 表情切换  
                    FaceChangeMessage faceChangeMessage = new FaceChangeMessage();
                    faceChangeMessage.flag = realData[0] & 0xff;
                    
                    EventBus.getDefault().post(faceChangeMessage);
                    send(SendResponse.getReply((byte) 0x02, (byte) SerialportConfig.reply_success));
                    break;
            }
        } catch (Exception e) {
            send(SendResponse.getReply((byte) commandId, (byte) SerialportConfig.reply_err));
            KLog.e(tag, "数据解析失败");
            e.printStackTrace();
        }
    }

    @Override
    public boolean send(SendResponse sendResponse) {
        return mSocketHelper.send(sendResponse);
    }

    @Override
    public void stop() {
        mSocketHelper.close();
    }

    @Override
    public void sendHeart() {
        mSocketHelper.send(SendResponse.getHeart());
    }

    @Override
    public void setSerialHelper(SocketHelper mSocketHelper) {
        this.mSocketHelper = mSocketHelper;
    }
}
